<template>
	<div class="order">
		<cl-crud ref="crud" @load="onLoad">
			<template #slot-datepicker>
				<div class="_top-filter">
					<!-- <date-picker
						style="width:350px;"
						:datas="datas"
						@change="val => refresh({ startTime: val[0], endTime: val[1], page: 1 })"
						@refresh="refresh({ startTime: '', endTime: '', page: 1 })"
					></date-picker>-->
					<el-date-picker
						v-model="datas"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						size="mini"
						value-format="yyyy-MM-dd"
						end-placeholder="结束日期"
						@change="dateChange"
					></el-date-picker>
					<div
						class="filter-btn"
						:class="[index == filterArrActive ? 'filter-btn-active' : '']"
						@click="filterArrActive = index"
						v-for="(item, index) in filterArr"
						:key="index"
					>
						{{ item }}
					</div>
					<div>
						<select-staff
							class="selects"
							ref="selectstaff"
							v-model="selects.staffId"
							@change="val => refresh({ staffId: val, page: 1 })"
						></select-staff>
					</div>

					<el-button
						@click="Export"
						v-permission="'crm:order:positionExport'"
						type="primary"
						style="margin-left:10px"
						size="mini"
					>
						<i class="el-icon-download"></i>导出报表
					</el-button>
				</div>
			</template>
			<template #table-column-fansNum="{scope}">
				<div>
					<div>微信个数：{{ scope.row.wechatNum }}</div>
					<div>总粉丝数：{{ scope.row.fansNum }}</div>
					<div>
						新增人数：
						<span style="color:red;font-size:16px">
							{{ scope.row.newFansNum }}
						</span>
					</div>
				</div>
			</template>

			<template #table-column-fansNum="{scope}">
				<div>
					<div>
						<span style="color:red;font-size:16px">
							{{ scope.row.newFansNum || '0' }}
						</span>
						/{{ scope.row.fansNum }}
					</div>
				</div>
			</template>
			<template #table-column-aTypeNum="{scope}">
				<div>
					<div>
						<span style="color:red;font-size:16px">{{ scope.row.newATypeNum }}</span>
						/{{ scope.row.aTypeNum }}
					</div>
				</div>
			</template>
			<template #table-column-fissionNum="{scope}">
				<div>
					<div>
						<span style="color:red;font-size:16px">{{ scope.row.newFissionNum }}</span>
						/{{ scope.row.fissionNum }}
					</div>
				</div>
			</template>
			<template #table-column-transform="{scope}">
				<div>{{ Number(scope.row.transform * 100).toFixed(2) }}%</div>
			</template>
			<template #table-column-validCommission="{scope}">
				<div>{{ scope.row.validCommission.toFixed(2) }}</div>
			</template>
			<template #table-column-averageProduct="{scope}">
				<div>{{ scope.row.averageProduct ? scope.row.averageProduct.toFixed(2) : 0 }}</div>
			</template>
			<template #slot-wechartInfo="{scope}">
				<wechartInfo
					:isSelf="isSelf"
					:times="scope.time"
					:userId="scope.userId"
					@resolt="val => (scope.wechatData = val)"
				></wechartInfo>
			</template>
			<template #slot-hdr-btn>
				<div class="close" @click="onclose">
					<i class="el-icon-close"></i>
				</div>
			</template>
			<template #slot-reportTime="{scope}">
				<reportTime
					:readonly="readonly"
					:value="scope.time ? scope.time : dateFormat(0).startTime"
					@change="val => (scope.time = val)"
				></reportTime>
			</template>
			<template #table-column-tkStatus="{scope}">
				<el-tag size="small" type="warning" v-if="scope.row.tkStatus == 3">订单结算</el-tag>
				<el-tag size="small" v-if="scope.row.tkStatus == 12">订单付款</el-tag>
				<el-tag size="small" type="info" v-if="scope.row.tkStatus == 13">订单失效</el-tag>
				<el-tag size="small" type="success" v-if="scope.row.tkStatus == 14"
					>订单成功</el-tag
				>
			</template>
			<!-- 查看按钮 -->
			<template #slot-add-info="{ scope }">
				<span class="check-btn" @click="checkInfo(scope.row)">查看</span>
			</template>
			<template #slot-edit-info="{ scope }">
				<span
					class="check-btn"
					@click="editInfo(scope.row)"
					v-if="scope.row.userId === userInfo.id"
					>编辑</span
				>
			</template>
		</cl-crud>
	</div>
</template>
<script>
import moment from 'moment';
import { dateFormat, download } from '@/utils/index';
import SelectStaff from '@/components/order/select-staff';
import wechartInfo from './component/wechartInfo';

import reportTime from './component/reportTime';
import { mapGetters } from 'vuex';
export default {
	data() {
		return {
			filterArr: ['今日', '昨日', '最近7天', '最近30天', '本月'],
			filterArrActive: 0,
			crud: null,
			crudList: [],
			selects: {
				staffId: ''
			},
			datas: [this.$route.query.startTime, this.$route.query.endTime],
			params: {
				startTime: this.$route.query.startTime,
				endTime: this.$route.query.endTime,
				...dateFormat(0)
			},
			readonly: false,
			isSelf: true // 是否 是自己的日报
		};
	},
	components: {
		wechartInfo,
		reportTime,
		SelectStaff
	},
	watch: {
		filterArrActive(val) {
			this.refresh({
				page: 1,
				size: 10,
				...dateFormat(val)
			});
		}
	},
	computed: {
		...mapGetters(['userInfo'])
	},
	mounted() {
		let start = moment()
			.hour(0)
			.minute(0)
			.second(0)
			.format('YYYY-MM-DD');

		let end = moment().format('YYYY-MM-DD');
		this.datas = [start, end];
	},
	methods: {
		dateFormat,
		onLoad({ ctx, app }) {
			this.crud = app;
			const { permission } = this.$store.state.menu;
			const { add, delete: del, update } = this.$service.reproing.staffdaily.permission;
			ctx.permission({
				add: permission.includes(add),
				delete: permission.includes(del),
				update: permission.includes(update)
			});
			ctx.service({
				page: this.$service.reproing.staffdaily.page,
				update: this.$service.reproing.staffdaily.update,
				delete: this.$service.reproing.staffdaily.delete,
				add: this.$service.reproing.staffdaily.add,
				info: params => {
					let item = this.crudList.filter(item => {
						return item.id === params.id;
					})[0];
					return Promise.resolve(item);
				}
			})
				.set('dict', {
					api: {
						list: 'list', // 全部数据
						add: 'add', // 新增
						update: 'update', // 修改
						delete: 'delete', // 删除
						info: 'info' // 详情
					},
					label: {
						add: '添加日报'
					},
					search: {
						query: 'salesStatus'
					}
				})
				.set('table', {
					columns: [
						{
							type: 'index',
							align: 'center',
							label: '序号',
							width: 80
						},
						{
							label: '员工名称',
							prop: 'username',
							align: 'center',
							minWidth: 100
						},
						{
							label: '时间',
							prop: 'time',
							align: 'center',
							minWidth: 150
						},
						{
							label: '微信个数',
							prop: 'wechatNum',
							align: 'center',
							emptyText: '0',
							minWidth: 100
						},
						{
							label: '粉丝新增/粉丝总数',
							prop: 'fansNum',
							align: 'center',
							minWidth: 130
						},
						{
							label: 'A类新增/A类总数',
							prop: 'aTypeNum',
							align: 'center',
							minWidth: 130
						},
						{
							label: '当天转化率(%)',
							prop: 'transform',
							align: 'center',
							minWidth: 120
						},
						{
							label: '裂变新增/裂变总数',
							prop: 'fissionNum',
							align: 'center',
							emptyText: '0',
							minWidth: 150
						},
						{
							label: '有效订单数',
							prop: 'validOrderNum',
							align: 'center',
							emptyText: '0',
							minWidth: 100
						},
						{
							label: '有效佣金',
							prop: 'validCommission',
							align: 'center',
							emptyText: '0',
							minWidth: 100
						},
						{
							label: '人均单产',
							prop: 'averageProduct',
							align: 'center',
							emptyText: '0',
							minWidth: 100
						}
					],
					op: {
						layout: ['slot-edit-info', 'slot-add-info']
					}
				})
				.set('upsert', {
					props: {
						title: '创建日报',
						width: '900px',
						'label-width': '100px',
						'close-on-press-escape': false,
						'close-on-click-modal': false
					},
					hdr: {
						layout: ['flex1', 'fullscreen', 'slot-hdr-btn']
					},
					items: [
						{
							prop: 'time',
							label: '日报时间：',
							span: 8,
							component: {
								name: 'slot-reportTime'
							},
							rules: [
								{
									required: true,
									message: '请选择时间',
									trrigger: 'blur'
								}
							]
						},
						{
							prop: 'username',
							label: '运营人：',
							span: 8,
							component: {
								name: 'usernames',
								attrs: {
									username: this.userInfo.username
								},
								props: {
									value: String
								},
								render() {
									return (
										<div>
											<el-tag size="mini" style="text-align-center">
												{this.value ? this.value : this.$attrs.username}
											</el-tag>
										</div>
									);
								}
							}
						},
						{
							prop: 'wxinfo',
							label: '微信号信息：',
							component: {
								name: 'slot-wechartInfo'
							}
						},
						{
							prop: 'evaluate',
							label: '自我评价：',
							component: {
								name: 'el-rate',
								attrs: {
									colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
									'show-text': true,
									style: '    position: relative;top: 7px;',
									disabled: false
								}
							}
						},
						{
							prop: 'remark',
							label: '今日总结：',
							component: {
								name: 'el-input',
								attrs: {
									type: 'textarea',
									disabled: false
								}
							}
						}
					],
					op: {
						visible: true
					}
				})
				.set('search', {
					key: {
						placeholder: '请输入员工名称'
					}
				})
				.set('layout', [
					['refresh-btn', 'add-btn', 'slot-datepicker', 'flex1', 'search-key'],
					['data-table'],
					['flex1', 'pagination']
				])
				.on('open', (isopen, form) => {
					this.readonly = isopen;
					isopen ? '' : app.setForm('evaluate', 5);
					if (!form) {
						//添加日报
						this.isSelf = true;
						this.crud.setData(
							'upsert.items[prop:evaluate].component.attrs.disabled',
							false
						);
						this.crud.setData(
							'upsert.items[prop:remark].component.attrs.disabled',
							false
						);
					}
				})
				.on('submit', (open, data, { next, done }) => {
					let { time, evaluate, remark, wechatData, id } = data;
					if (open) {
						if (data.username == this.userInfo.username) {
							delete data.username;
							next({ time, evaluate, remark, wechatData, id });
						} else {
							this.$message.error('无法修改他人的日报');
							done();
						}
					} else {
						delete data.username;
						next({ time, evaluate, remark, wechatData, id });
					}
				})
				.on('refresh', async (params, { next }) => {
					const { list } = await next(params);
					this.crudList = list;
				})
				.done();
			app.refresh(this.params);
		},
		// 查看信息
		checkInfo(row) {
			this.isSelf = false;
			this.crud.setData('upsert.op.visible', false);
			this.crud.edit(row);
			this.crud.setData('upsert.items[prop:evaluate].component.attrs.disabled', true);
			this.crud.setData('upsert.items[prop:remark].component.attrs.disabled', true);
		},
		editInfo(row) {
			this.isSelf = true;
			this.crud.setData('upsert.op.visible', true);
			this.crud.edit(row);
			this.crud.setData('upsert.items[prop:evaluate].component.attrs.disabled', false);
			this.crud.setData('upsert.items[prop:remark].component.attrs.disabled', false);
		},
		onclose() {
			if (!this.isSelf) {
				this.crud.close(); //不是自己的日报，直接关闭，不需要询问
				return;
			}
			this.$confirm('是否保存数据?', '', {
				confirmButtonText: '保存',
				cancelButtonText: '不保存'
			})
				.then(() => {
					this.crud.submit();
				})
				.catch(() => {
					this.crud.close();
				});
		},
		// 日报导出
		Export() {
			this.$service.reproing.staffdaily
				.export(this.params)
				.then(res => {
					download({
						data: res,
						fileName: `员工报表-${moment().format('YYYY-MM-DD HH:mm:ss')}`
					});
				})
				.catch(err => console.err(err));
		},
		dateChange(val) {
			if (!val) {
				this.refresh({ startTime: '', endTime: '', page: 1 });
				return;
			}
			if (moment(new Date()).isBefore(val[1], 'day')) {
				let end = moment().format('YYYY-MM-DD');
				this.datas = [val[0], end];
				this.refresh({ startTime: val[0], endTime: end, page: 1 });
				return;
			}
			this.refresh({ startTime: val[0], endTime: val[1], page: 1 });
		},
		refresh(params) {
			if (params.startTime && params.endTime) {
				this.datas = [params.startTime, params.endTime];
			}
			this.params = {
				...this.params,
				...params
			};
			this.crud.refresh(params);
		}
	}
};
</script>
<style lang="stylus" scoped>
.crud-index {
    padding 10px
}
.order {
    height 100%
}
._top-filter .el-date-editor {
    border-left 1px solid #DCDFE6
}

.el-range-editor.is-active {
    border-color #FF4400
}

.close {
	display: flex;
    align-items: center;
    justify-content: center;
    height: 25px;
    width: 40px;
    border: 0;
    background-color: #fff;
    cursor: pointer;
    outline: none;
}
.filter-btn {
	width:83px;
	height: 28px;
	text-align center
	line-height: 28px;
	background:rgba(255,255,255,1);
	border:1px solid rgba(0,0,0,0.14901960784313725);
	font-size 14px
	color #606266
	margin-left 10px
	border-radius:4px;
	cursor: pointer;
	transition all .3s
}
.filter-btn-active {
	background:#FD5822
	color #ffffff
	border:1px solid #ffffff;
}
.check-btn {
	color: #065ffe;
	margin-left: 15px;
	cursor pointer;
}
</style>
